package com.gitee.cashzhang27.test.boot.other.filter;

import com.gitee.cashzhang27.test.boot.other.util.BodyReaderHttpServletRequestWrapper;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/07/03 16:08
 */
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "httpServletRequestReplaced")
public class HttpServletRequestReplacedFilter implements Filter {

  @Override
  public void init(FilterConfig arg0) throws ServletException {
    log.info("HttpServletRequestReplacedFilter init successful!");
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    ServletRequest requestWrapper = null;
    if(request instanceof HttpServletRequest) {
      requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
    }
    // 获取请求中的流如何，将取出来的字符串，再次转换成流，然后把它放入到新request对象中。
    // 在chain.doFiler方法中传递新的request对象
    if(requestWrapper == null) {
      chain.doFilter(request, response);
    } else {
      chain.doFilter(requestWrapper, response);
    }
  }

  @Override
  public void destroy() {

  }
}

